from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
from bs4 import BeautifulSoup
import requests
import re

def setting():
    headers = {
        "Accept": "text / html, application / xhtml + xml, application / xml;q = 0.9, image / webp, image / apng, * / *;q = 0.8",
        "Accept - Encoding": "gzip, deflate",
        "Accept - Language": "zh - CN, zh;q = 0.9, en;q = 0.8",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
    }

    rootUrl = "http://192.168.200.247/opac/item.php?"

    proxies = {
        "http": "http://qf:qf3.1415@221.232.137.211:10086/"
    }

    return headers, rootUrl, proxies


# 拼接参数
def joinStrC(items):
    str = ""
    for item in items:
        a = item[0] + "=" + item[1]
        str = str + "&" + a

    return str.strip("&")


def index(request):
    headers, rootUrl, proxies = setting()
    # 拼接成完整请求连接
    marc_no = request.POST.get("marc_no","")
    c = "marc_no={}".format(marc_no)
    url = rootUrl + c

    data = {
        "bookInfo": [],
    }

    web_data = requests.get(url=url, headers=headers, proxies=proxies).content.decode("utf-8", "ignore")
    soup = BeautifulSoup(web_data, "html5lib")

    # #获取列表信息
    linkList = soup.select('#item_detail dl')[0:-2]
    bookListInfo = formBookListInfo(linkList)

    data["bookInfo"] = bookListInfo

    return HttpResponse(json.dumps(data), content_type="application/json")


# 获取图书相关信息
def formBookListInfo(dataList):

    allBookInfo = []
    for dd in dataList:
        bookListInfo = {
            "key": "",
            "value": "",
            "href": ""
        }

        bookListInfo['key'] = dd.select("dt")[0].text
        bookListInfo['value'] = dd.select("dd")[0].text
        try:
            href = dd.select("dd a")[0]['href']
            px = re.compile(r"\?.*$")
            array = px.findall(str(href))
            bookListInfo['href'] = array[0]
        except:

            bookListInfo['href'] = ''
        allBookInfo.append(bookListInfo)


    return allBookInfo







